"use client";
import { SearchProps } from "antd/es/input";
import TableCom from "../TableCom";
import style from "./index.module.scss";
import Search from "antd/es/input/Search";
import {
  Button,
  Dropdown,
  MenuProps,
  Modal,
  Popconfirm,
  Select,
  Space,
  TableProps,
  message,
} from "antd";
import {
  auditPost,
  delPost,
  getPostById,
  getPostObs,
  getPosts,
  getType,
  updatePost,
} from "@/api";
import { useEffect, useState } from "react";
import { OptionType, PostType, selectedPostRowsType } from "@/configs/types";
import TextArea from "antd/es/input/TextArea";
import { updateParamsName } from "@/utils";
import { SEVER_URL } from "@/configs/constant";
import DetailsMadal from "../DetailsModal";
import { IPostData } from "@/app/PostContentView/page";

export default function PostManage() {
  //用户管理表头
  const postManageColumns = [
    {
      title: "封面",
      dataIndex: "postPhoto",
      key: "postPhoto",
      align: "center",
      width: "108px",
      render: (_: any, record: any) => {
        return (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={`${SEVER_URL}${record.postPhoto}`}
            alt=""
            width={60}
            height={60}
          ></img>
        );
      },
    },
    {
      title: "作者名称",
      dataIndex: "postAuthorName",
      key: "postAuthorName",
      align: "center",
      width: "140px",
    },

    // {
    //   title: "内容",
    //   dataIndex: "postContent",
    //   key: "postContent",
    //   align: "center",
    //   width: "200px",
    //   render: (_: any, record: any) => {
    //     return (
    //       <div
    //         style={{
    //           width: "200px",
    //           height: "20px",
    //           overflow: "hidden",
    //           whiteSpace: "nowrap",
    //           textOverflow: "ellipsis",
    //         }}
    //       >
    //         {record.postContent}
    //       </div>
    //     );
    //   },
    // },
    {
      title: "标题",
      dataIndex: "postTitle",
      key: "postTitle",
      align: "center",
    },
    {
      title: "摘要",
      dataIndex: "postSummary",
      key: "postSummary",
      align: "center",
      ellipsis: true,
    },
    {
      title: "类型",
      dataIndex: "postType",
      key: "postType",
      align: "center",
    },

    {
      title: "审核状态",
      dataIndex: "postStatus",
      key: "postStatus",
      align: "center",
      width: "120px",
      render: (_: any, record: any) => {
        return (
          <>
            <Select
              value={record.postStatus}
              style={{ width: 100 }}
              onChange={(value) => handleStatusChange(record.id, value)}
              options={[
                { value: 2, label: "未通过" },
                { value: 1, label: "通过" },
                { value: 0, label: "待审核" },
              ]}
            ></Select>
          </>
        );
      },
    },
    {
      title: "未通过审核原因",
      dataIndex: "cause",
      key: "cause",
      align: "center",
      ellipsis: true,
      width: "200px",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      align: "center",
      width: "200px",
      render: (_: any, record: any) => (
        <Space size="middle">
          <Popconfirm
            title="删除这条数据"
            description="你确定要删除这条数据吗"
            onConfirm={() => deletePost(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
          <a onClick={() => handleOpenDetailsModal(record.id)}>详情</a>
        </Space>
      ),
    },
  ];
  const [textAreaValue, setTextAreaValue] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [detailsModel, setDetailsModal] = useState(false);
  const [posts, setPosts] = useState<any[]>([]);
  const [selectedRowsData, setSelectedRowsData] =
    useState<selectedPostRowsType>({
      selectedRowKeys: [],
      selectedRows: [],
    });
  const [pageOptions, setPageOptions] = useState({ current: 1, pageSize: 10 });
  const [filedIds, setFiledIds] = useState<number[]>([]);
  const [types, setTypes] = useState<OptionType[]>([]);
  const [total, setTotal] = useState(0);
  const [postDetails, setPostDetails] = useState<IPostData>();
  const auditNoPass = () => {
    setFiledIds(selectedRowsData.selectedRowKeys as number[]);
    setIsModalOpen(true);
  };
  // 对话框
  const handleOk = () => {
    statusData(textAreaValue);
    setIsModalOpen(false);
  };
  const statusData = async (cause: string = "") => {
    const res = await auditPost({
      postIds: filedIds,
      notPassId: 2,
      cause,
    });
    if (res.data.code === 200) {
      getPost(pageOptions.current, pageOptions.pageSize);
      message.success(res.data.msg);
    } else message.error(res.data.msg);
    setFiledIds([]);
    setTextAreaValue("");
  };
  const handleCancel = () => {
    setFiledIds([]);
    setTextAreaValue("");
    setIsModalOpen(false);
  };
  //获取帖子信息
  const getPostDetails = async (id: number) => {
    const res = await getPostById({ id });
    if (res.data.code === 200) {
      setPostDetails(res.data.data.post);
    }
  };
  //打开详情页
  const handleOpenDetailsModal = async (id: number) => {
    await getPostDetails(id);
    setDetailsModal(true);
  };

  const items: MenuProps["items"] = [
    {
      label: (
        <span
          style={{ width: "100px" }}
          onClick={() => onBulkOperations("auditPost")}
        >
          审核通过
        </span>
      ),
      key: "0",
    },
    {
      label: (
        <span style={{ width: "100px" }} onClick={auditNoPass}>
          审核不通过
        </span>
      ),
      key: "1",
    },
    {
      type: "divider",
    },
  ];

  //分页
  const handlePageChange = (current: number, pageSize: number) => {
    setPageOptions({ current, pageSize });
    getPost(current, pageSize);
  };
  const paginationOptions = {
    current: pageOptions.current,
    pageSize: pageOptions.pageSize,
    showQuickJumper: true,
    total,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: handlePageChange,
  };
  const deletePost = async (id: number) => {
    const res = await delPost([id]);
    getPost(pageOptions.current, pageOptions.pageSize);
    res.data.code === 200
      ? message.success(res.data.msg)
      : message.error(res.data.msg);
  };
  // 多选
  const rowSelection: TableProps<PostType>["rowSelection"] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: PostType[]) => {
      setSelectedRowsData({ selectedRowKeys, selectedRows });
    },
    getCheckboxProps: (record) => ({
      disabled: record.postTitle === "Disabled User", // Column configuration not to be checked
      name: record.postTitle,
    }),
    selectedRowKeys: selectedRowsData.selectedRowKeys,
  };
  //直接修改状态
  const handleStatusChange = async (id: number, status: number) => {
    let res;
    if (status === 0) {
      res = await updatePost({ postStatus: status, id });
      if (res.data.code === 200) {
        getPost(pageOptions.current, pageOptions.pageSize);
        message.success(res.data.msg);
      } else message.error(res.data.msg);
    }
    if (status === 1) {
      res = await auditPost({ postIds: [id], passId: 1 });
      if (res.data.code === 200) {
        getPost(pageOptions.current, pageOptions.pageSize);
        message.success(res.data.msg);
      } else message.error(res.data.msg);
    }
    if (status === 2) {
      setIsModalOpen(true);
      setFiledIds([id]);
    }
  };

  //  根据标题查询
  const onPostNameSearch: SearchProps["onSearch"] = async (value, _e, info) => {
    const res = await getPosts({ postTitle: value });
    res.data.code === 200 && setPosts(res.data.data.records);
  };
  //根据状态查询

  const handleSearchByStatus = async (value: number) => {
    const res = await getPostObs({ postStatus: value });
    res.data.code === 200 && setPosts(res.data.data.records);
  };

  //根据帖子类型查询
  const handleSearchByType = (value: number, option: any) => {
    option.value === "all" ? getPost(1, 20) : getPost(1, 20, option.label);
  };

  const getPost = async (
    pageNum: number,
    pageSize: number,
    postType?: string
  ) => {
    const res = await getPosts({
      pageNum,
      pageSize,
      postType,
    });
    setPosts(res.data.data.records);
    setTotal(res.data.data.total);
  };

  //查询帖子种类
  const getPostType = async () => {
    const res = await getType({ differ: "post", pageNum: 1, pageSize: 20 });
    const dataArr: OptionType[] = updateParamsName(
      res.data.data.records,
      "typeName",
      "id"
    );
    dataArr.unshift({ value: "all", label: "全部" });
    res.data.code === 200 && setTypes(dataArr);
  };
  useEffect(() => {
    localStorage.getItem("token") && getPost(1, 10);
    getPostType();
  }, []);
  //批量操作
  const onBulkOperations = async (type: string) => {
    let res;
    if (type === "auditPost") {
      res = await auditPost({
        postIds: selectedRowsData.selectedRowKeys,
        passId: 1,
      });
    } else if (type === "delete") {
      res = await delPost(selectedRowsData.selectedRowKeys);
    }
    if (res!.data.code === 200) {
      getPost(pageOptions.current, pageOptions.pageSize);
      setSelectedRowsData({ selectedRowKeys: [], selectedRows: [] });
      message.success(res!.data.msg);
    } else message.error(res!.data.msg);
  };

  return (
    <div className={style["Container"]}>
      <div className={style["header"]}>
        <Space>
          <Search
            placeholder="请输入帖子名称"
            onSearch={onPostNameSearch}
            style={{ width: 200 }}
            maxLength={32}
          />
          <Button onClick={() => onBulkOperations("delete")}>批量删除</Button>
          <Dropdown menu={{ items }}>
            <Button>批量审核</Button>
          </Dropdown>
          <Select
            placeholder={"请选择类型"}
            options={types}
            onChange={handleSearchByType}
            style={{ width: 200 }}
          >
            类型筛选
          </Select>
          <Select
            placeholder={"请选择状态"}
            options={[
              { value: 2, label: "审核未通过" },
              { value: 1, label: "审核通过" },
              { value: 0, label: "待审核" },
            ]}
            onChange={handleSearchByStatus}
            style={{ width: 200 }}
          >
            状态查询
          </Select>
        </Space>
      </div>
      <div className={style["content"]}>
        <TableCom
          dataSource={posts}
          columns={postManageColumns}
          paginationOptions={paginationOptions}
          rowSelection={rowSelection}
          className={style["table"]}
        />
        <Modal
          title="未通过审核的原因"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <TextArea
            value={textAreaValue}
            onChange={(e) => setTextAreaValue(e.target.value)}
            autoSize={{ minRows: 6, maxRows: 20 }}
          ></TextArea>
        </Modal>
        <DetailsMadal
          className={style["madalWrapper"]}
          open={detailsModel}
          setOpen={setDetailsModal}
          data={postDetails}
        ></DetailsMadal>
      </div>
    </div>
  );
}
